using Eno.Application.Dto;
using Eno.Application.Services;
using Eno.Domain.Entity.App;
using Eno.Infrastructure.Tools;
using Microsoft.AspNetCore.Mvc;

namespace Eno.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
public class RoleController : ControllerBase
{
    private readonly RoleService _service;

    private readonly ILogService _logService;

    public RoleController(RoleService roleService, ILogService logService)
    {
        _service = roleService;
        _logService = logService;
    }

    [HttpGet]
    public async Task<IActionResult> GetAllRolesAsync()
    {
        try
        {
            var roles = await _service.GetAllRolesAsync();
            await _logService.LogInfoAsync("查询所有角色", "RoleController", new { Count = roles.Count() });
            return Ok(Tips<IEnumerable<AppRole>>.Success(roles, "查询所有角色成功"));
        }
        catch (Exception ex)
        {
            await _logService.LogErrorAsync("查询所有角色失败", ex, "RoleController");
            return Ok(Tips<IEnumerable<AppRole>>.Fail(Enumerable.Empty<AppRole>()));
        }
    }

    [HttpPost]
    public async Task<IActionResult> AddRoleAsync(RoleDto roleDto)
    {
        try
        {
            var role = await _service.AdditonRole(roleDto);
            if (role == 0) return Ok(Tips<string>.Fail(""));
            await _logService.LogInfoAsync("新增角色成功");
            return Ok(Tips<int>.Success(role, "新增角色操作成功"));
        }
        catch (Exception ex)
        {
            await _logService.LogErrorAsync("添加用户异常", ex, "RoleController", new { roleDto.RoleName });
            return Ok(Tips<int>.Fail(0, 3474, "注册失败"));
        }

    }

    [HttpPost("{guid}")]
    public async Task<IActionResult> EditRoleAsync(Guid guid, RoleDto roleDto)
    {
        var role = await _service.UpdateRole(guid, roleDto);
        if (role == 0) return Ok(Tips<string>.Fail(""));
        return Ok(Tips<int>.Success(role, "修改角色操作成功"));
    }

    [HttpDelete("{guid}")]
    public async Task<IActionResult> DelRoleAsync(Guid guid)
    {
        var role = await _service.DeleteRole(guid);
        if (role == 0) return Ok(Tips<string>.Fail(""));
        return Ok(Tips<int>.Success(role, "删除角色操作成功"));
    }
}